package com.hkjtgc.pcr_app.fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.hkjtgc.pcr_app.R
import com.hkjtgc.pcr_app.adapter.*
import com.hkjtgc.pcr_app.database.DatabaseManager
import com.hkjtgc.pcr_app.model.TodoInfoDO
import com.hkjtgc.pcr_app.ui.BindingMachineActivity
import com.hkjtgc.pcr_app.ui.MainActivity
import com.hkjtgc.pcr_app.ui.QRCodeActivity
import com.hkjtgc.pcr_app.util.Constant
import com.hkjtgc.pcr_app.util.SharedPreferencesUtils
import com.hkjtgc.pcr_app.util.StatusBarUtil.finish
import com.hkjtgc.pcr_app.util.ToastUtil
import kotlinx.coroutines.*
import java.util.*

@RequiresApi(Build.VERSION_CODES.M)
@SuppressLint("SetTextI18n")
class HomeFragment : Fragment(), CoroutineScope by MainScope() {

    private lateinit var recyclerView: RecyclerView
    var adapter: ToDoListAdapter? = null
    private lateinit var tvTitle: TextView
    var todoList: MutableList<TodoInfoDO> = mutableListOf()
    var start = false
    var cTodoInfoDO: TodoInfoDO? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_home, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        init()
    }


    @OptIn(DelicateCoroutinesApi::class)
    @SuppressLint("StringFormatMatches", "NotifyDataSetChanged")
    private fun init() {
        tvTitle = requireActivity().findViewById(R.id.tv_title)
        requireActivity().findViewById<TextView>(R.id.begin_new_test).setOnClickListener {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startActivity(Intent(requireActivity(), QRCodeActivity::class.java))
                finish()
            }
        }
        val mainActivity = activity as MainActivity
        mainActivity.list?.let {
            todoList.addAll(it)
        }

        recyclerView = requireActivity().findViewById(R.id.rvBaseRecycler)
        val layoutManger = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
        recyclerView.layoutManager = layoutManger
//        tvTitle.text = "待处理检测(共0条)"


        adapter = ToDoListAdapter(this,todoList, object : ToDoListAdapter.ItemClick {

            override fun clickStart(position: Int) {
                if (start) {
                    ToastUtil.toastShort(requireActivity(), "当前有检测进行中，请稍后再试")
                    return
                }
                cTodoInfoDO = todoList[position]
                Collections.swap(todoList, position, 0)
                start = true
//                if(position==0){
//                    holder.begin.text = "进行中"
//                    holder.begin.setBackgroundResource(R.drawable.title_abnormal)
//                }else{
//                    holder.begin.text = "等待"
//                    holder.begin.setBackgroundResource(R.drawable.btn_cycle_bg)
//                }
                //todo 点击的按钮显示停止，按钮背景变红色，其余按钮变灰色且不可点击（或变色，点击toast：当前检测正在进行中，请稍后再试!）
                adapter!!.notifyDataSetChanged()
                val handler = Handler()
                handler.postDelayed({
                    stop()
                }, 3000) // 延时3s执行run内代码
            }

            override fun clickDelete(position: Int) {
                delete(position)
            }

            //点击到binding详情页面并传值
            override fun clickListItem(position: Int) {
                var todoInfo: TodoInfoDO = todoList[position]
                SharedPreferencesUtils.getSPInstance(requireActivity())
                    .putSP(Constant.TODO_INFO, Gson().toJson(todoInfo))
                val intent = Intent(requireActivity(), BindingMachineActivity::class.java)
                intent.putExtra("data", "true")
                startActivity(intent)
            }
        })
        recyclerView.adapter = adapter
    }

    fun delete(position: Int) {
        todoList.removeAt(position)
        tvTitle.text = "待处理检测(共${todoList.size}条)"
        adapter!!.notifyDataSetChanged()
        val todo = todoList[position]
        DatabaseManager.db.todoDao().delete(todo)
    }

    fun stop() {
        start = false
        cTodoInfoDO = null
        delete(0)
    }


    @SuppressLint("NotifyDataSetChanged")
    override fun onResume() {
        super.onResume()
        GlobalScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                runCatching {
                    DatabaseManager.saveApplication(requireActivity().application)
                    val newTodoList = DatabaseManager.db.todoDao().getAll()?: emptyList()
                    cTodoInfoDO?.let {
                        val index = newTodoList.indexOf(it)
                        if(index!=-1){
                            Collections.swap(newTodoList, index, 0)
                        }
                    }
                    todoList.clear()
                    todoList.addAll(newTodoList)
                }
            }
            adapter?.let {
                it.notifyDataSetChanged()
                tvTitle.text = "待处理检测(共${todoList.size}条)"
            } ?: run {
                init()
            }
        }
    }
}